package utils;

import dao.UserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisUtil {
    //会话工厂创建
    private SqlSessionFactory sqlSessionFactory;
    //使用单例模式创建会话工厂对象
    //静态代码块
    static {
        String resource = "mybatis-config.xml";
        SqlSession sqlSession = null;
        //加载配置文件
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //创建合适工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //创建会话
            sqlSession = sqlSessionFactory.openSession();
            //执行查询
            List<User> users = sqlSession.getMapper(UserDao.class).findAll();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            sqlSession.close();




    }



    //静态方法
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();



    }
}
